package logobj.ftpUtil.analysis;

import logobj.utils.TimeUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class AnalysisFtpUtilBase {
    /***
     *
     * 关闭ftp
     * */
    public void disconnect(FTPClient ftpClient){
        if(null != ftpClient){
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 删除文件
     *
     * @return 是否删除成功
     */
    public boolean deleteFile(FTPClient ftpClient, String remotePath, ArrayList namelist ) {
        boolean result = true;
        try {
            boolean changeResult = ftpClient.changeWorkingDirectory(remotePath);
            if (!changeResult) {
                throw new RuntimeException("切换目录失败");
            }
            int num = namelist.size();
            //循环删除文件
            String filename="";
            for(int i =0;i<num ;i++){
                filename = String.valueOf(namelist.get(i));
                //循环删除log日志文件
                if(filename.indexOf(".log") != -1 ){
                    result = result && ftpClient.deleteFile(filename);
                }
            }
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public  Map<String , ArrayList> getFtpFileNameSize(FTPClient ftpClient){
        ArrayList namelist = new ArrayList();
        ArrayList sizelist = new ArrayList();
        try {
            //获取该目录权下的所有文件
            FTPFile[] fs=ftpClient.listFiles();
            for(FTPFile ff:fs) {
                namelist.add(ff.getName());
                sizelist.add(ff.getSize());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String , ArrayList> ftpfileinfo = new HashMap<>();
        ftpfileinfo.put("namelist",namelist);
        ftpfileinfo.put("sizelist",sizelist);
        return ftpfileinfo;
    }

    /**
     * 下载文件
     *
     * param ftpConfig  配置
     * @param remotePath 远程目录
     * @param fileName   文件名
     * @param localPath  本地目录
     * @param localName  本地文件名
     * @return 是否下载成功
     */
    public boolean download(FTPClient ftpClient, String remotePath, String fileName, String localPath, String localName) {
        try {
            boolean changeResult = ftpClient.changeWorkingDirectory(remotePath);
            if (!changeResult) {
                throw new RuntimeException("切换目录失败");
            }
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            File file = new File(localPath, localName);
            if (!file.getParentFile().exists()) {
                boolean mkdirsResult = file.getParentFile().mkdirs();
                if (!mkdirsResult) {
                    throw new RuntimeException("创建目录失败");
                }
            }
            if (file.exists()) {
                System.out.println("["+ TimeUtils.getStringNowDate()+"]:在本地已存在该日志，执行删除操作！");
                file.delete();
            }
            boolean createFileResult = file.createNewFile();
            if (!createFileResult) {
                throw new RuntimeException("创建文件失败");
            }
            OutputStream outputStream = new FileOutputStream(file);
            boolean result = ftpClient.retrieveFile(fileName, outputStream);
            outputStream.flush();
            outputStream.close();
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 登录ftp
     *
     * @param ftpConfig 配置
     * @return 是否登录成功
     * @throws IOException
     */
    public  FTPClient connectClient( AnalysisFtpConfig ftpConfig)  {
        FTPClient ftpClient =  new FTPClient();
        // 连接FTP服务器
        try {
            ftpClient.connect(ftpConfig.getIp(), ftpConfig.getPort());
            // 登录FTP
            ftpClient.login(ftpConfig.getUserName(), ftpConfig.getPassword());
            // 正常返回230登陆成功
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                throw new RuntimeException("连接ftp失败");
            }
            ftpClient.setControlEncoding("GBK");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ftpClient;
    }

}
